let util = require("./util")
let app = getApp();
let getApi = util.wxPromisify(wx.request, "request"),
    getStorageSync = util.wxPromisify(wx.getStorageSync),
    showLoading = util.wxPromisify(wx.showLoading),
    hideLoading = util.wxPromisify(wx.hideLoading),
    redirectTo = util.wxPromisify(wx.redirectTo),
    requestPayment = util.wxPromisify(wx.requestPayment),
    switchTab = util.wxPromisify(wx.switchTab),
    showToast = util.wxPromisify(wx.showToast),
    NetworkType = util.wxPromisify(wx.getNetworkType),
    showNavigationBarLoading = util.wxPromisify(wx.showNavigationBarLoading),
    hideNavigationBarLoading = util.wxPromisify(wx.hideNavigationBarLoading),
    chooseImage = util.wxPromisify(wx.chooseImage),
    uploadFile = util.wxPromisify(wx.uploadFile, "upfile"),
    showModal = util.wxPromisify(wx.showModal),
    showActionSheet = util.wxPromisify(wx.showActionSheet),
    navigateToMiniProgram = util.wxPromisify(wx.navigateToMiniProgram),
    getSystemInfo = util.wxPromisify(wx.getSystemInfo);
//带session的header
const HEADERSESSION = app.globalData.header;
//请求的地址
const BASEURL = app.globalData.baseUrl;
/**
 * 查看购物车商品信息
 */
const getCart = () => {
    return getApi({
        url: BASEURL + '/applet/cart/cartOrderSettlement.do',
        header: HEADERSESSION,
        data: {
            shopCode: app.globalData.common.shopCode
        }
    })
}
/**
 * 购物车结算查询信息
 * @param {优惠券id} voucherMemberId 
 * @param {*是否自动选择} isAuto 
 */
const getCartV1 = (voucherMemberId = '', isAuto = "") => {
    return getApi({
        url: BASEURL + '/applet/cart/v1/cartOrderSettlement.do',
        header: HEADERSESSION,
        data: {
            shopCode: app.globalData.common.shopCode,
            voucherMemberId: voucherMemberId,
            isAuto: isAuto
        }
    })
}
/**
 * 创建订单
 * @param {*} shopCode 店铺编码
 */
const createOrder = (voucherMemberId = "", formId) => {
    return getApi({
        url: BASEURL + '/applet/order/v1/createGoodsOrder.do',
        header: HEADERSESSION,
        data: {
            shopCode: app.globalData.common.shopCode,
            platform: 6,
            voucherMemberId,
            formId
        }
    })
}
/**
 * 通过待付款订单号查询支付信息
 * @param {*} code 待付款订单号
 */
const getOrderByCode = (code) => {
    return getApi({
        url: BASEURL + '/applet/order/getOrderByOrderCode.do',
        header: HEADERSESSION,
        data: {
            orderCode: code
        }
    })
}
/**
 * 获取用户余额
 */
const getBalance = () => {

    return getApi({
        url: BASEURL + '/wxappletMember/getBalance.do',
        header: HEADERSESSION
    })
}
/**
 * 获取用户级别
 */
const getLevel = () => {
    return getApi({
        url: BASEURL + '/wxappletMember/getMember.do',
        header: HEADERSESSION
    })
}
/**
 * 查询订单
 * @param {*} status 订单状态： 100/null =>全部订单； 0=》待支付订单 ；2=>已完成
 * @param {*} pageNum 当前页码 默认1
 * @param {*} pageSize 每页显示数量 默认10
 */
const getOrders = (status, pageNum = 1, pageSize = 10) => {

    return getApi({
        url: BASEURL + '/applet/order/getOrderList.do',
        header: HEADERSESSION,
        data: {
            orderStatus: status,
            pageNum: pageNum,
            pageSize: pageSize
        }
    })
}
/**
 * 获取支付需要的参数，如果是微信支付，会把获取的参数作为调用微信支付的参数
 * @param {*} ordeCode 订单号
 * @param {*} payType 支付方式 1=》微信支付  4=》余额支付
 *  platform: 6  来源
 */
const getPayParams = (ordeCode, payType) => {
    return getApi({
        url: BASEURL + '/applet/pay/doPay.do',
        header: HEADERSESSION,
        data: {
            orderCode: ordeCode,
            payType: payType,
            platform: 6
        }
    })
}
/**由于新加入了免密支付,原有的支付逻辑需要修改,此接口提供统一的支付入口,由服务端判断有密码支付还是免密支付
 * 获取支付需要的参数，如果是微信支付，会把获取的参数作为调用微信支付的参数
 * @param {*} ordeCode 订单号
 * @param {*} payType 支付方式 1=》微信支付  4=》余额支付
 * platform: 6  来源
 */
const newgetPayParams = (ordeCode, payType) => {
    return getApi({
        url: BASEURL + '/applet/pay/v1/pay.do',
        header: HEADERSESSION,
        data: {
            orderCode: ordeCode,
            payType: payType,
            platform: 6
        }
    })
}
/**
 * 获取待付款订单数量
 */
const waitPayNum = () => {
    return getApi({
        url: BASEURL + '/applet/order/waitPayNum.do',
        header: HEADERSESSION,
    })
}
/**
 * 获取验证码
 * @param {*手机号} phonenum
 */
const acquireCode = (phonenum) => {
    return getApi({
        url: BASEURL + '/verify/code.do',
        data: {
            mobile: phonenum
        }
    })
}
/**
 * 登录
 * @param {*手机号} phonenum
 * @param {*验证码} identifyCode
 */
const login = (phonenum, identifyCode) => {
    return getApi({
        url: BASEURL + '/wxappletMember/bind.do',
        data: {
            mobile: phonenum,
            vc: identifyCode
        }
    })
}
/**
 * 绑定手机号
 * @param {*手机号} mobile
 * @param {*验证码} vc
 */
const bindPhone = (openId, platform, shopCode, userInfo, mobile, vc, recommendId) => {
    return getApi({
        url: BASEURL + '/applet/v1/register.do',
        // header: {     Cookie: HEADERSESSION.Cookie,     'content-type':
        // 'application/json' },
        header: HEADERSESSION,
        method: "POST",
        data: {
            openId: openId,
            platform: platform,
            shopCode: shopCode,
            userInfo: userInfo,
            mobile: mobile,
            vc: vc,
            recommendId: recommendId
        }
    })
}
/**
 * 检测人脸质量接口
 * @param {*文件路径} filePath
 */
const faceCheck = (filePath) => {
    return uploadFile({
        url: BASEURL + '/wxappletMember/applet/validateImgQuality',
        filePath: filePath,
        name: "file",
        header: {
            Cookie: HEADERSESSION.Cookie,
            'content-type': 'multipart/form-data'
        }
    })
}
/**
 * 获取上传头像或人脸到阿里云oss的签名参数
 * @param {*} businessType 1=>人脸的标 识2=>头像标识
 */
const getImageSign = (businessType) => {
    return getApi({
        url: BASEURL + '/applet/image/getImageSign.do',
        method: "POST",
        header: {
            Cookie: HEADERSESSION.Cookie,
            'content-type': 'application/x-www-form-urlencoded'
        },
        data: {
            businessType: businessType
        }
    })
}
/**
 *
 * @param {*上传的实体} obj
 * @param {*上传到阿里云的存储路径s} filePath
 */
const uptoAliOSS = (obj, filePath) => {
    return uploadFile({
        url: obj.host,
        filePath: filePath,
        name: "file",
        formData: {
            OSSAccessKeyId: obj.accessid,
            policy: obj.policy,
            Signature: obj.signature,
            key: obj.filePath + "/" + obj.fileName,
            success_action_status: "200",
            callback: obj.callback
        }
    })
}
/**
 * 检测用户是否上传了人脸识别照片
 */
const hasUploadImg = () => {
    return getApi({
        url: BASEURL + '/wxappletMember/applet/getFaceImg.do',
        header: HEADERSESSION
    })
}
/**
 * 获取免密参数
 * @param {*门店号} shopCode
 */
const getFreePayParams = (shopCode = '') => {

    return getApi({
        url: BASEURL + '/applet/freepay/v1/sign/params.do',
        header: HEADERSESSION,
        data: {
            shopCode: shopCode
        }
    })
}
/**
 * 查看用户微信和余额免密状态
 * @param {*门店号} shopCode
 */
const freePayStatus = (shopCode = '') => {

    return getApi({
        url: BASEURL + '/applet/freepay/v3/sign/state.do',
        header: HEADERSESSION,
        data: {
            shopCode: shopCode
        }
    })
}
/**
 *微信支付 解约
 * @param {*} shopCode
 */
const rescidFreePay = (shopCode = '') => {
    return getApi({
        url: BASEURL + '/applet/freepay/v1/rescind.do',
        header: HEADERSESSION,
        data: {
            shopCode: shopCode
        }
    })
}
// 
/**
 * 用户修改密码/签约前/支付前的密码验证（余额）
 */
const validatePwd = (password) => {
    return getApi({
        url: BASEURL + '/applet/balance/pwd/check.do ',
        header: HEADERSESSION,
        data: {
            password
        }
    })
}
/**
 * 余额明细
 * @param {*} pageNum 
 * @param {*} pageSize 
 */
const balanceDetail = (pageNum, pageSize = 15) => {
    return getApi({
        url: BASEURL + '/wxappletMember/applet/getBalanceLogs.do',
        header: HEADERSESSION,
        data: {
            pageNum: pageNum,
            pageSize: pageSize
        }
    })
}
/**购物车优惠券信息 */
const getCartCoupons = () => {
    return getApi({
        url: BASEURL + '/applet/cart/getCartCoupons.do',
        header: HEADERSESSION,
        data: {
            shopCode: app.globalData.common.shopCode
        }
    })
}
/**商铺优惠券信息 */
const getreserveCoupons = () => {
    return getApi({
        url: BASEURL + '/applet/reserve/cart/coupons.do',
        header: HEADERSESSION,
        data: {
            shopCode: app.globalData.common.shopCode
        }
    })
}
/**商铺优惠券信息 */
const getNewReserveCoupons = () => {
    return getApi({
        url: BASEURL + '/applet/reserve/cart/coupons.do',
        header: HEADERSESSION,
        data: {
            shopCode: app.globalData.common.reserveShopCode,
            type: 2
        }
    })
}

/** 新注册用户优惠券*/
const newMemVoucher = () => {
    return getApi({
        url: BASEURL + '/applet/coupon/newMemVoucher.do',
        header: HEADERSESSION,
    })
}
/**
 * 首单券
 * @param {*订单号} orderCode 
 */
const firstOrder = (orderCode) => {
    return getApi({
        url: BASEURL + '/applet/order/return/vouchers.do',
        header: HEADERSESSION,
        data: {
            orderCode
        }
    })
}
/**
 * 日常券
 * @param {数量} number 
 */
const getNewCoupon = (number = 99) => {
    return getApi({
        url: BASEURL + '/applet/coupon/getNewCoupon.do',
        header: HEADERSESSION,
        data: {
            number
        }
    })
}
/**
 * 升级券
 */
const upgradeVouchers = () => {
    return getApi({
        url: BASEURL + '/applet/coupon/getUpgradeVouchers.do',
        header: HEADERSESSION,
    })
}
/**
 * 获取充值优惠列表
 */
const getRechargePromotionList = () => {
    return getApi({
        url: BASEURL + '/applet/recharge/getRechargePromotionList.do',
        header: HEADERSESSION,
    })
}
/**
 * 获取充值优惠
 * @param {充值金额} rechargeAmount 
 */
const getRechargePromotion = (rechargeAmount) => {
    return getApi({
        url: BASEURL + '/applet/recharge/getRechargePromotion.do',
        header: HEADERSESSION,
        data: {
            rechargeAmount


        }
    })
}
/**
 * 创建充值订单
 * @param {*充值数额} rechargeAmount 
 */
const createRechargeOrder = (rechargeAmount) => {
    return getApi({
        url: BASEURL + '/applet/order/v1/createRechargeOrder.do',
        header: HEADERSESSION,
        data: {
            rechargeAmount: rechargeAmount,
            shopCode: app.globalData.common.shopCode
        }
    })
}

/**
 * 检查API的在当前的微信版本是否可用
 * @param {*需要检测的API} API
 */
const compatibilityHandler = (API) => {
    if (API) {
        return
    } else {
        // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
        wx.showModal({
            title: '提示',
            content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
        })
    }
}
const handleFetchError = (des) => {
    wx.showToast({
        title: des,
        image: '../../image/warn.png',
        duration: 3000
    })
}
/**
 *
 * @param {*当前的调用者} self
 * @param {* 提示的文案} my_toast_tip
 * @param {*选择的模板 } template
 * @param {*模板自动消失的时间} time
 */
const showMyToast = (self, my_toast_tip, time = 2000, template = 'my_toast') => {
    self.setData({
        template: template, //my_toast
        my_toast_tip: my_toast_tip
    })
    setTimeout(() => {
        self.setData({
            template: '', //my_toast
            my_toast_tip: ''
        })
    }, time)
}
const loadingText = (config = {
    title: '加载中',
    mask: true
}) => {
    showLoading(config);
    showNavigationBarLoading()

}
const hideLoadingText = () => {
    hideLoading();
    hideNavigationBarLoading()
}
module.exports = {
    getApi,
    showLoading,
    hideLoading,
    getCart,
    getBalance,
    createOrder,
    getOrders,
    getOrderByCode,
    requestPayment,
    getPayParams,
    newgetPayParams,
    redirectTo,
    switchTab,
    acquireCode,
    login,
    getSystemInfo,
    showToast,
    bindPhone,
    compatibilityHandler,
    handleFetchError,
    getLevel,
    showMyToast,
    NetworkType,
    loadingText,
    hideLoadingText,
    chooseImage,
    faceCheck,
    showModal,
    getImageSign,
    uptoAliOSS,
    hasUploadImg,
    showActionSheet,
    getFreePayParams,
    navigateToMiniProgram,
    balanceDetail,
    rescidFreePay,
    freePayStatus,
    waitPayNum,
    getCartV1,
    getCartCoupons,
    getreserveCoupons,
    getNewReserveCoupons,
    newMemVoucher,
    firstOrder,
    getNewCoupon,
    upgradeVouchers,
    getRechargePromotion,
    getRechargePromotionList,
    createRechargeOrder,
    validatePwd
}